local BillBoardPanel = require "View/BillBoard/BillBoardPanel"
local RankList = require "View/BillBoard/RankList/BillBoardRankListPanel"
local UnlockTipPanel = require "View/BillBoard/RankList/SubRankUnlockTipPanel"
require "Net/TrialHandel"
---@class UISystemBillBoard : UIBase
UISystemBillBoard = UIBase.New(PanelResNames.UISystemBillBoard)
local t = UISystemBillBoard

local m_process_type = nil

function t.Init(pageIndex,battleBackFunc)
    t.pageIndex = pageIndex or 3
    t.battleBackFunc = battleBackFunc;
    UIBase.Init(t)

end

function t:OnCreate()
    self:RegisterEvent(Config.EventType.Billboard_rank_reddot_refresh, self.RefreshRedDot)

    self.backbutton = self:GetChild("backbutton")
    self.ctrlType = self:GetController("type")
    self.ctrlSocial = self:GetController("ctrlSocial")
    self.btnInfo = self:GetChild("info")
    --self.endTimeText = self:GetChild("endtime")
    self.lockCtrl = self:GetController("lock");
    --self.btnPower = self:GetChild("zhanli")
    --self.btnSocial = self:GetChild("shejiao")
    --self.btnCost = self:GetChild("xiaohao")
    self.btnBillboard = self:GetChild("gonggao")
    self.ctrlTips = self:GetController("tips")
    self.otherList = self:GetChild("List_PlayRank")
    self.myRank = self:GetChild("Com_MyRank")
    self.red_stage = self:GetChild("Btn_Stage"):GetChild("UIRedDots")
    self.red_ClimbTower = self:GetChild("Btn_ClimbTower"):GetChild("UIRedDots")
    self.red_Mythic = self:GetChild("Btn_Mythic"):GetChild("UIRedDots")
    self.red_btnreward =  self:GetChild("btn_reward"):GetChild("UIRedDots")
    self.red_battleStory = self:GetChild("Btn_BattleStory"):GetChild("UIRedDots")
    --[[self.btnRankList = {
        self.btnCost,
        self.btnPower,
        self.btnSocial,
        self.btnBillboard,
    }]]
    self.ctrlOnRank = self:GetController("ctrlOnRank")
    ---@type BillBoardPanel
    self.billBoardPanel = self:CreateComponent(BillBoardPanel, self:GetChild("BillBoards"))
    ---@type BillBoardRankListPanel
    self.partRankList = self:CreateComponent(RankList, self:GetChild("ranklist"))
    ---@type Billboard_SubRankUnlockTipPanel
    self.unlockTipPanel = self:CreateComponent(UnlockTipPanel,self:GetChild("lockTips"))
    TrialHandel.SendTrialsWorldRank()
    --mythicDungeonsHandler.ReqInstanceGetRanks()
    mythicDungeonsProHandler.ReqInstanceGetRanks()
    self:RegisterOnClick(self:GetChild("btn_reward"), self.onClick_showProcessReward)
    self:RegisterOnClick(self.btnInfo, self.ClickInfo)
    self:RegisterOnClick(self.backbutton, self.ClickClose)
    self:RegisterOnChanged(self.ctrlType, self.CtrlTypeChanged)
    self:RegisterEvent(Config.EventType.BillboardUpdate, self.BillboardUpdateMsg)
    self:RegisterEvent(Config.EventType.FreashRoleInfoOther, self.ShowOtherPlayerInfo)
    self:RegisterEvent(Config.EventType.FreashDungeonList,self.OtherRankData)
    self:SetDynamicList(self.otherList,self.OtherRankItem,nil,true)

    self:RefreshRedDot()
end

function t:OtherRankItem(index,obj)
    self:SetMyRank(self.otherData[index+1],obj,index)
end

function t:RefreshRedDot()
    local r1 = logicMgr.BillboardMgr.NeedShowRedDot(EnumConst.BillRankType.Stage)
    local r2 = logicMgr.BillboardMgr.NeedShowRedDot(EnumConst.BillRankType.YongJie)
    local r3 = logicMgr.BillboardMgr.NeedShowRedDot(EnumConst.BillRankType.Relic)
    local r4 = logicMgr.BillboardMgr.NeedShowRedDot(EnumConst.BillRankType.MagicTravel)

    self.red_stage:GetController("c1").selectedIndex = r1 and 2 or 0
    self.red_ClimbTower:GetController("c1").selectedIndex = r3 and 2 or 0
    self.red_Mythic:GetController("c1").selectedIndex = r2 and 2 or 0
    self.red_battleStory:GetController("c1").selectedIndex = r4 and 2 or 0

    if self.ctrlType.selectedIndex == 4 then
        self.red_btnreward:GetController("c1").selectedIndex = r1 and 2 or 0
    elseif self.ctrlType.selectedIndex == 5 then
        self.red_btnreward:GetController("c1").selectedIndex = r2 and 2 or 0
    elseif self.ctrlType.selectedIndex == 6 then
        self.red_btnreward:GetController("c1").selectedIndex = r3 and 2 or 0
    elseif self.ctrlType.selectedIndex == 7 then
        self.red_btnreward:GetController("c1").selectedIndex = r4 and 2 or 0
    end
end

function t:SetFirst(data)
    local obj = self:GetChild("Btn_TopPlayer")
    local ctr_rank = obj:GetController("rank")
    local playerName = obj:GetChild("PlayerName")
    local lv = obj:GetChild("PlayerLevel")
    local data_txt = obj:GetChild("PlayerLayers")
    local icon = obj:GetChild("RankHead"):GetChild("head"):GetChild("HeadIcon")
    local frame = obj:GetChild("RankHead"):GetChild("frame")
    local ctrl = obj:GetController("type")
    local playCtrl = obj:GetController("Player")
    obj.onClick:Clear()
    if data then
        local txtDataScore = nil
        playCtrl.selectedIndex = 0
        if self.ctrlType.selectedIndex==4 then
            local stageCfg = G.dataTable["t_stage"][tostring(data.score)]
            txtDataScore = stageCfg.f_ChapterId .. "-" .. stageCfg.f_StageNum;
        elseif self.ctrlType.selectedIndex == 7 then
            local stageCfg = G.dataTable["t_stagehardmode"][tostring(data.score)]
            if stageCfg then
                txtDataScore = stageCfg.f_ChapterId .. "-" .. stageCfg.f_StageNum;
            else
                txtDataScore = "1-0"
            end
        end
        self:SetPlayerIcon(icon,data.headIcon,frame,data.headFrame)
        playerName.text = data.name
        data_txt.text = txtDataScore or tostring(data.score)
        lv.text = data.level
        if tostring(data.playerId) ~= logicMgr.HeroManager.GetRoleId() then
            obj.onClick:Add(function()
                roleInfoHandler.sendreqOtherRoleInfo(tostring(data.playerId));
            end)
        end
    else
        playCtrl.selectedIndex = 1
        icon.url = EnumConst.AtlasPath.CommonUI.."icon_hero_kb91"
        frame.url = ""
        playerName.text = getLanguage("BillboardRankNeedPlayer")
    end
    if self.ctrlType.selectedIndex == 4 or self.ctrlType.selectedIndex == 7 then
        ctrl.selectedIndex = 0
    elseif self.ctrlType.selectedIndex ==5 then
        ctrl.selectedIndex = 1
    else
        ctrl.selectedIndex = 2
    end
    ctr_rank.selectedIndex = 0
end

function t:SetMyRank(data,obj,index,isme)
    if index == nil then return end
    if not isme then
        index = index + 1
    end
    local ctr_rank = obj:GetController("ranking")
    local playerName = obj:GetChild("PlayerName")
    local lv = obj:GetChild("Text_PlayerLevel")
    local rank = obj:GetChild("Rank")
    local data_txt = obj:GetChild("Level")
    local icon = obj:GetChild("Head"):GetChild("head"):GetChild("HeadIcon")
    local frame = obj:GetChild("Head"):GetChild("frame")
    local typeCtrl = obj:GetController("Type")
    obj.onClick:Clear()
    if data then
        local txtDataScore = nil
        if self.ctrlType.selectedIndex==4 then
            local stageCfg = G.dataTable["t_stage"][tostring(data.score)]
            txtDataScore = stageCfg.f_ChapterId .. "-" .. stageCfg.f_StageNum;
        elseif self.ctrlType.selectedIndex == 7 then
            local stageCfg = G.dataTable["t_stagehardmode"][tostring(data.score)]
            if stageCfg then
                txtDataScore = stageCfg.f_ChapterId .. "-" .. stageCfg.f_StageNum;
            else
                txtDataScore = "1-0"
            end
        end
        if isme then
            self:SetPlayerIcon(icon,logicMgr.HeroManager.GetRoleInfo("pic"),frame,logicMgr.HeroManager.GetRoleInfo("picFrame"))
            playerName.text = logicMgr.HeroManager.GetRoleName()
            data_txt.text = txtDataScore or tostring(data.score)
            lv.text = logicMgr.HeroManager.GetRoleLevel()
        else
            obj.onClick:Add(function()
                if tostring(data.playerId) ~= logicMgr.HeroManager.GetRoleId() then
                    roleInfoHandler.sendreqOtherRoleInfo(tostring(data.playerId));
                end
            end)
            self:SetPlayerIcon(icon,data.headIcon,frame,data.headFrame)
            playerName.text = data.name
            data_txt.text = txtDataScore or tostring(data.score)
            lv.text = data.level
        end
    else
        icon.url = EnumConst.AtlasPath.CommonUI.."icon_hero_kb91"
        frame.url = ""
        playerName.text = getLanguage("BillboardRankNeedPlayer")
    end
    if index <= 3 and index >=1 then
        ctr_rank.selectedIndex = index-1
    else
        ctr_rank.selectedIndex = 3
        rank.text = index
    end
    if isme then
        if index<=0 then
            rank.text = "未上榜"
        end
    end
    if self.ctrlType.selectedIndex == 4 or self.ctrlType.selectedIndex == 7 then
        typeCtrl.selectedIndex = 0
    elseif self.ctrlType.selectedIndex ==5 then
        typeCtrl.selectedIndex = 1
    else
        typeCtrl.selectedIndex = 2
    end
end

function t:OtherRankData(msg)
    self.otherData = {}
    self.mydata = {}
    local index = self.ctrlType.selectedIndex
    if index == 4 then
        self.otherData = msg.ranks
        self.mydata.rank = msg.myRank
        self.mydata.score = msg.myScore
    elseif index == 5 then
        self.otherData = logicMgr.MythicDungeonsManager.rankList.ranks
        self.mydata = logicMgr.MythicDungeonsManager.rankList.myRank
    elseif index == 6 then
        self.otherData = logicMgr.TowerManager.getRanks(1)
        self.mydata = logicMgr.TowerManager.getMyRank(1)
        self.mydata.score = self.mydata.data.score
    elseif index == 7 then
        self.otherData = logicMgr.StoryHardManager.GetRanks()
        self.mydata.rank, self.mydata.score = logicMgr.StoryHardManager.GetMyRankInfo()
    end
    self.otherList.numItems = 0
    if self.otherData ~= nil and #self.otherData > 0 then
        self.otherList.numItems = #self.otherData -1
        self:SetFirst(self.otherData[1])
    else
        self:SetFirst()
    end
    self:SetMyRank(self.mydata,self.myRank,self.mydata.rank,true)

    self:RefreshRedDot()
end

function t:OnEnable()
    self:Refresh()
    if t.pageIndex == self.ctrlType.selectedIndex then
        self:CtrlTypeChanged()
    end
    NoticeHandler.ReqSynRankNotice()
    local mgr = logicMgr.NoticeManager
    --UIRedDots.addViewListen(PanelNames.UISystemBillBoard, self.fguiObj.name .. self.btnCost.name, self.btnCost,
    --        Config.RedDotsType.Billboard, mgr.PartBigType.cost)
    --UIRedDots.addViewListen(PanelNames.UISystemBillBoard, self.fguiObj.name .. self.btnPower.name, self.btnPower,
    --        Config.RedDotsType.Billboard, mgr.PartBigType.power)
    --UIRedDots.addViewListen(PanelNames.UISystemBillBoard, self.fguiObj.name .. self.btnSocial.name, self.btnSocial,
    --        Config.RedDotsType.Billboard, mgr.PartBigType.social)
    --UIRedDots.addViewListen(PanelNames.UISystemBillBoard, self.fguiObj.name .. self.btnBillboard.name, self.btnBillboard,
    --        Config.RedDotsType.Billboard, mgr.PartBigType.billboard)

    mgr.CancelRedDotsDelayCheck()
    self:RegisterEvent(Config.EventType.TouchAnyKey,self.HideLockTip)
end
function t:OnDisable()

    UIRedDots.removeViewEvent(PanelNames.UISystemBillBoard)
    logicMgr.NoticeManager.RedDotsDelayCheckReq()
    self:RemoveEvent(Config.EventType.TouchAnyKey)
end
function t:OnDestroy()
end
function t:Refresh()
    self.ctrlType.selectedIndex = t.pageIndex
   self:RefreshCtrlRank()
    self:RefreshBtnRank()
end
function t:RefreshCtrlRank()
    local rank = logicMgr.NoticeManager.GetMySelfSubRankLevel()
    self.ctrlOnRank.selectedIndex = rank > 0 and 0 or 1
end


function t:RefreshBtnRank()
    --3榜都移除了
    self.lockCtrl.selectedIndex = 2
    --[[local flag = not logicMgr.NoticeManager.IsOpen() or logicMgr.NoticeManager.IsTimeEnd()
    for k, v in pairs(self.btnRankList) do
        if k == 4 then
            if FuncOpenManager.isOpen(Config.FuncOpenType.OperationNotice, false) then
                if flag then
                    self.lockCtrl.selectedIndex = 2
                else
                    self.lockCtrl.selectedIndex = 1;
                end
            else
                self.lockCtrl.selectedIndex = 0;
            end
        else
            self.lockCtrl.selectedIndex = 1;
            v.visible = not flag
        end
    end]]
end
function t:CtrlTypeChanged()
    local index = self.ctrlType.selectedIndex
    if index == 0 then
        --self.partRankList:Open(logicMgr.NoticeManager.PartBigType.cost)
    elseif index == 1 then
        --self.partRankList:Open(logicMgr.NoticeManager.PartBigType.power)
    elseif index == 2 then
       -- self.partRankList:Open(logicMgr.NoticeManager.PartBigType.social)
    elseif index == 3 then
        self.billBoardPanel:Open()
    elseif index == 4 then
        dungeonHandler.ReqDungeonRankList()
        m_process_type = EnumConst.BillRankType.Stage
    else
        if index == 5 then
            m_process_type = EnumConst.BillRankType.YongJie
        elseif index == 6 then
            m_process_type = EnumConst.BillRankType.Relic
        elseif index == 7 then
            m_process_type = EnumConst.BillRankType.MagicTravel
        end
        self:OtherRankData()
    end
end

function t:ShowLockTip(bigRank,subRank)
    self.ctrlTips.selectedIndex = 1
    self.unlockTipPanel:Refresh(bigRank,subRank)
end

function t:HideLockTip()
    self.ctrlTips.selectedIndex = 0
end
function t:ClickClose()
    closeUI(PanelResNames.UISystemBillBoard)
end

function t:onClick_showProcessReward()
    -- showUI(PanelResNames.UIBillboardRankReward)
    showUI(PanelNames.UIBillRankReward, m_process_type)
end

function t:ClickInfo()
    local index = self.ctrlType.selectedIndex
    if index == 0 then
        -- cost
        logicMgr.UIShowManager.ShowCommonTips("HelpTitle7", "HelpDes7")
    elseif index == 1 then
        --power
        logicMgr.UIShowManager.ShowCommonTips("HelpTitle8", "HelpDes8")
    elseif index == 2 then
        --social
        logicMgr.UIShowManager.ShowCommonTips("HelpTitle9", "HelpDes9")
    end
end
function t:BillboardUpdateMsg()
    self:Refresh()
end
function t:ShowOtherPlayerInfo(info)
    if not panelMgr:IsOpen("UICity") then
        --uicity 不用重复打开
        showUI(PanelNames.UIPlayerShow, info,nil,false,t.battleBackFunc)
    end
end

return t